package com.feng.cloud.common.interceptor;

import com.feng.cloud.common.configure.properties.GatewayTokenProperties;
import com.feng.cloud.common.exception.auth.AuthStatus;
import com.feng.cloud.common.response.BaseResponse;
import com.feng.cloud.common.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName ServerProtectInterceptor
 * @Description TODO
 * @Author Better Feng
 * @Date 2020/1/6 9:52
 * @Version 1.0
 **/
@Slf4j
public class ServerProtectInterceptor implements HandlerInterceptor {

    private final GatewayTokenProperties gatewayTokenProperties;

    public ServerProtectInterceptor(GatewayTokenProperties gatewayTokenProperties) {
        this.gatewayTokenProperties = gatewayTokenProperties;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取 Gateway Token
        String requestHeader = request.getHeader(gatewayTokenProperties.getName());
        if (!StringUtils.equals(requestHeader, gatewayTokenProperties.getSecretKey())) {
            WebUtils.makeResponse(response, MediaType.APPLICATION_JSON_VALUE,
                    HttpServletResponse.SC_FORBIDDEN,new BaseResponse(AuthStatus.USER_FORBIDDEN));
            return false;
        }
        return true;
    }
}
